import { PLAYER_STATUS } from "../../STATUS";
import TWEEN, {
	L_ANI_TIME,
	B_ANI_TIME,
	M_ANI_TIME,
	S_ANI_TIME,
	Tween
} from "../../core/Tween";
import {
	vueStageComponentWrapper,
	on,
	init_loader_number_res
} from "../../core/componentGenerator";
export default vueStageComponentWrapper("home", {
	data() {
		return {
			player_number: 2,
			room_id: "",
			is_create_room_dialog_open: false,
			is_join_room_dialog_open: false,
			is_game_log_open: false,
			is_game_log_loading: false,
			game_logs: [],
			bulletin: ""
		};
	},
	resources: {
		bg: "home/Home_BJ.png",
		avatar_ring: "home/Avatar_ring.png",
		random_match: "home/自由匹配.png",
		create_room: "home/Build_01.png",
		join_room: "home/Join_01.png",
		close_button: "home/Close_01.png",
		create_room_dialog: "home/renshu_UI_01.png",
		create_room_title: "home/renshu_UI_02.png",
		two_player: "home/two_01.png",
		three_player: "home/three_01.png",
		four_player: "home/four_01.png",
		join_room_dialog: "home/Home_UI_02.png",
		join_room_input: "home/Box_4_01.png",
		num_reset: `home/Remove_01.png`,
		num_del: `home/Delete_01.png`,
		random_queue_bg: "home/bisai_tip.png",
		cancel_btm: "home/Cancel_01.png",
		confirm_btm: "home/choujiang_confirm.png",

		// 水豆房卡
		points_icon: "home/points.png",
		cards_icon: "home/Roomcard_01.png",
		asset_icon_bg: "home/Gold_02.png",
		asset_add_btm: "home/add.png",

		// 工具欄
		menu_btm: "home/Menu_01.png",

		// 公告栏
		notify_icon: "home/gonggao02.png",

		// 游戏记录
		game_log_close_btm: "home/go_01.png",
		game_log_title: "home/jilv.png",
		game_log_bg: "home/Record_BJ.png",
		game_log_item: "home/Record_UI_02.png",
		confirm_dialog: "home/bisai_tip.png",

		// 分享
		share_tip: "home/分享.png",
		ILNR:init_loader_number_res(),
		num(loader) {
			for (let n = 0; n <= 9; n += 1) {
				loader.add("num_" + n, `home/Number${n}_01.png`);
			}
		}
	},
	next_stages: ["wait-gamer"], // 用于预加载
	created() {
		wx_promise.then(function change_wx_share(wx) {
			if (!window._wx_onMenuShareAppMessage_config) {
				setTimeout(() => {
					change_wx_share(wx);
				}, 200);
				return;
			}
			const new_wx_share_config = Object.assign(
				{},
				window._wx_onMenuShareAppMessage_config,
				{
					desc: "不用下载，即点即玩，快来赢水豆，可以兑换手机话费哦！"
				}
			);
			wx.onMenuShareAppMessage(new_wx_share_config);
		});
		const { unwatchers, app, loader, offs } = this;
		/* 公告 */
		socket.emit("bulletin"); // 请求公告
		offs[offs.length] = on(socket, "bulletin", bulletin => {
			console.log("bulletin changed", bulletin);
			this.bulletin = bulletin;
		});

		const ani_tween = new TWEEN();
		app._ticker.add(() => {
			// 动画控制器
			ani_tween.update();
		});
		this.draw_app = () => {
			console.log("DRAW HOME");
			const loader = this.loader;
			if (!loader) {
				// maybe run on after destroyed
				return;
			}
			this.clearWatch();
			ani_tween.clear();
			const resources = loader.resources;
			console.log(resources);
			app.stage.destroy();
			app.stage = new PIXI.Container();
			const stage = new PIXI.Container();
			const top_layer = new PIXI.Container();
			app.stage.addChild(stage);
			app.stage.addChild(top_layer);
			const { width, height } = app.renderer;
			const bg = new PIXI.Sprite(resources.bg.texture);
			bg.maxWidth(width);
			if (bg.height < height) {
				bg.maxHeight(height);
			}
			bg.x = width / 2; //- bg.width / 2;
			bg.y = height / 2; //- bg.height / 2;
			const bg_cur_scale = bg.scale.x;
			const bg_tar_scale = bg_cur_scale * 1.2;
			bg.anchor.set(0.5, 0.5);
			const ani_1 = ani_tween
				.Tween(bg.scale)
				.to({ x: bg_tar_scale, y: bg_tar_scale }, L_ANI_TIME)
				.easing(TWEEN.Easing.Quadratic.Out);
			const ani_2 = ani_tween
				.Tween(bg.scale)
				.to({ x: bg_cur_scale, y: bg_cur_scale }, L_ANI_TIME)
				.easing(TWEEN.Easing.Quadratic.Out);
			ani_1.onComplete(() => {
				ani_2.start();
			});
			ani_2.onComplete(() => {
				ani_1.start();
			});
			ani_1.start();
			// ani_tween.Tween(bg)
			//   .to({ rotation: 3 }, L_ANI_TIME)
			//   .start()
			stage.addChild(bg);

			const header = new PIXI.Container();
			stage.addChild(header);

			// 用户信息
			const $userhead_clip = new PIXI.Graphics();
			$userhead_clip.beginFill(0x0, 1);
			const clip_r = Math.min(height, width) * 0.1 / 2 * 1.6;
			$userhead_clip.drawShape(new PIXI.Circle(clip_r, clip_r, clip_r));
			$userhead_clip.endFill();
			$userhead_clip.x = height * 0.02;
			$userhead_clip.y = height * 0.025;
			const userhead_clip_bound = $userhead_clip.getBounds();
			header.addChild($userhead_clip);
			const $avatar_ring = new PIXI.Sprite(resources.avatar_ring.texture);
			$avatar_ring.width = userhead_clip_bound.width * 1.1;
			$avatar_ring.height = userhead_clip_bound.height * 1.1;
			$avatar_ring.x =
				userhead_clip_bound.x - userhead_clip_bound.width * 0.05;
			$avatar_ring.y =
				userhead_clip_bound.y - userhead_clip_bound.height * 0.05;
			header.addChild($avatar_ring);
			let $userhead;
			let $username;
			let $userid;

			const fontSize = userhead_clip_bound.height / 4;
			unwatchers[unwatchers.length] = this.$watch(
				"player.info",
				info => {
					const { headimgurl, username } = info;
					const player_id = (this.player.id || "").substr(0, 6);
					if ($userhead) $userhead.destroy();
					if ($username) $username.destroy();
					if ($userid) $userid.destroy();
					$userhead = new PIXI.Sprite.fromImage(
						`${server_href}/proxy?src=${encodeURIComponent(headimgurl)}`
					);
					const $userhead_texture = $userhead.texture;
					$userhead_texture.on("update", function update(
						tex,
						is_keep
					) {
						$userhead.width = userhead_clip_bound.width;
						$userhead.height = userhead_clip_bound.height;
						$userhead.x = userhead_clip_bound.x;
						$userhead.y = userhead_clip_bound.y;
						$userhead.mask = $userhead_clip;
						if (!is_keep) {
							$userhead_texture.off("update", update);
						}
					});
					$userhead_texture.emit(
						"update",
						null,
						!$userhead_texture.valid
					);

					$username = new PIXI.Text(username, {
						fontSize: fontSize * 1.5,
						fill: 0xffffff
					});
					$username.alpha = 0.9;
					if (width >= height) {
						$username.x = userhead_clip_bound.right + fontSize / 2;
						$username.y = userhead_clip_bound.top + fontSize * 0.2;
					} else {
						$username.x = userhead_clip_bound.left + fontSize / 2;
						$username.y =
							userhead_clip_bound.bottom + fontSize * 0.2;
					}

					$userid = new PIXI.Text(`ID: ${player_id}`, {
						fontSize: fontSize * 1.2,
						fill: 0xffffff
					});
					$userid.x = $username.x;
					$userid.y = $username.y + fontSize * 2;

					header.addChildBefore($userhead, $avatar_ring);
					header.addChildBefore($username, $avatar_ring);
					header.addChildBefore($userid, $avatar_ring);
				},
				{ immediate: true }
			);

			/* 房卡信息*/
			const $user_assets_info = new PIXI.Container();
			header.addChild($user_assets_info);
			{
				$user_assets_info.children.slice().forEach($c => $c.destroy());

				const infoFontSize = userhead_clip_bound.width / 4 * 1.2;
				const text_style = {
					fontSize: infoFontSize,
					fill: 0xffffff
				};
				const user_name_id_right = Math.max(
					$username.right,
					$userid.right
				);
				const asset_type_list = ["cards", "points"];
				asset_type_list.forEach((type, i) => {
					const $asset_info = new PIXI.Container();
					$user_assets_info.addChild($asset_info);
					const $asset_bg = new PIXI.Sprite(
						resources.asset_icon_bg.texture
					);
					$asset_bg.maxHeight(userhead_clip_bound.width * 0.6);
					if (
						user_name_id_right +
							$asset_bg.width * 1.2 * asset_type_list.length +
							userhead_clip_bound.width * 2 <
						width
					) {
						$asset_bg.x = i * $asset_bg.width * 1.2;
					} else {
						$asset_bg.y = i * $asset_bg.height * 1.2;
					}
					$asset_info.addChild($asset_bg);
					const $asset_icon = new PIXI.Sprite(
						resources[type + "_icon"].texture
					);
					$asset_icon.maxHeight(userhead_clip_bound.width * 0.7);
					$asset_icon.x = $asset_bg.x - $asset_icon.width * 0.2;
					$asset_icon.y = $asset_bg.centerY - $asset_icon.height / 2;
					$asset_info.addChild($asset_icon);
					const $asset_val = new PIXI.Text(``, text_style);
					$asset_info.addChild($asset_val);
					$user_assets_info["set_" + type] = function(text) {
						$asset_val.text = text;
						$asset_val.x =
							$asset_bg.x +
							$asset_bg.width / 2 -
							$asset_val.width / 2;
						$asset_val.y =
							$asset_bg.centerY - $asset_val.height / 2;
					};
					const $add_asset_btm = new PIXI.Sprite(
						resources.asset_add_btm.texture
					);

					const _rate = 0.84;
					$add_asset_btm.maxHeight($asset_bg.height * _rate);
					$add_asset_btm.x = $asset_bg.right - $add_asset_btm.width;
					$add_asset_btm.y =
						$asset_bg.y + $asset_bg.height * (1 - _rate) / 2;
					$add_asset_btm.hover();
					const $server_dialog = new PIXI.Alert(
						"需要房卡请联系客服\n\nQQ: 5356460\n\n微信号: asihui",
						{
							parent: top_layer,
							view_width: width,
							view_height: height,
							dialog_texture: resources.confirm_dialog.texture,
							yes_texture: "确定",
							open: false,
							can_mask_close: true
						}
					);
					if (type === "cards") {
						$add_asset_btm.bindTap(() => {
							$server_dialog.open();
						});
					} else if (type === "points") {
						const share_tip = new PIXI.Graphics();
						share_tip.beginFill(0, 0.5);
						share_tip.drawRect(0, 0, width, height);
						share_tip.endFill();
						top_layer.addChild(share_tip);
						const share_tip_content = new PIXI.Sprite(
							resources.share_tip.texture
						);
						share_tip_content.maxWidthHeight(
							width * 0.5,
							height * 0.3
						);
						share_tip_content.x = width - share_tip_content.width;
						share_tip_content.y = 0;
						share_tip.addChild(share_tip_content);
						share_tip.visible = false;
						share_tip.interactive = true;
						share_tip.bindTap(() => {
							share_tip.visible = false;
						});

						let $point_dialog = new PIXI.Confirm(
							"水豆兑换方式：\n联系客服，每1000水豆可获得50电话充值卡\n水豆获得方式：\n1.分享后，好友点击进入完成登录，\n　即可获得10水豆。\n2.每充值一张房卡可获得10水豆。\n3.随机匹配游戏胜利赚取水豆。",
							{
								parent: top_layer,
								view_width: width,
								view_height: height,
								dialog_texture: resources.confirm_dialog
									.texture,
								yes_texture: "联系客服",
								no_texture: "立刻分享",
								fontSizeRate: 16,
								open: false,
								close_btm_texture: resources.close_button
									.texture
							}
						).on("close", res => {
							console.log(res);
							if (res) {
								$server_dialog.open();
							} else {
								share_tip.visible = true;
							}
						});
						$add_asset_btm.bindTap(() => {
							$point_dialog.open();
						});
					}
					$asset_info.addChild($add_asset_btm);

					$user_assets_info.addChild($asset_info);
				});
				if (width >= height) {
					$user_assets_info.x =
						user_name_id_right + userhead_clip_bound.width * 0.5;
					$user_assets_info.y =
						userhead_clip_bound.y + userhead_clip_bound.width * 0.2;
				} else {
					$user_assets_info.x =
						width / 2 - $user_assets_info.width / 2;
					$user_assets_info.y =
						userhead_clip_bound.centerY -
						$user_assets_info.height / 2 +
						userhead_clip_bound.width * 0.2;
				}

				asset_type_list.forEach(type => {
					unwatchers[unwatchers.length] = this.$watch(
						"player.info." + type,
						value => {
							console.log(type, "changed", value);
							$user_assets_info["set_" + type](value || 0);
						},
						{ immediate: true }
					);
				});
			}
			/* 菜單按鈕 */
			const $menu_btm = new PIXI.Sprite(resources.menu_btm.texture);
			$menu_btm.maxHeight(userhead_clip_bound.height * 0.8);

			$menu_btm.y = userhead_clip_bound.centerY - $menu_btm.height / 2;
			$menu_btm.x =
				width - $menu_btm.width - userhead_clip_bound.width * 0.2;
			$menu_btm.hover();
			$menu_btm.bindTap(() => {
				this.showGameLogPage();
			});
			header.addChild($menu_btm);

			/* 公告 */
			const $notify_icon = new PIXI.Sprite(resources.notify_icon.texture);
			$notify_icon.maxWidth(userhead_clip_bound.width * 0.6);
			$notify_icon.x = userhead_clip_bound.x;
			$notify_icon.y = header.height + userhead_clip_bound.width * 0.6;
			stage.addChild($notify_icon);
			const bulletin_font_size = $notify_icon.height * 0.8;
			const bulletin_left = $notify_icon.x + $notify_icon.width * 1.5;
			const bulletin_wordWrapWidth =
				width - bulletin_font_size - bulletin_left;
			const $bulletin = new PIXI.Text("公告加载中……", {
				fontSize: bulletin_font_size,
				// fill: 0xFFFFFF,
				dropShadow: true,
				dropShadowBlur: 3,
				dropShadowDistance: 2,
				dropShadowColor: 0x2233ff,
				fill: [0xe286f5, 0xffeeff],
				wordWrap: true,
				wordWrapWidth: bulletin_wordWrapWidth
			});
			$bulletin.x = bulletin_left;
			$bulletin.y = $notify_icon.y;
			stage.addChild($bulletin);

			unwatchers[
				unwatchers.length
			] = this.$watch(
				"bulletin",
				bulletin => {
					$bulletin.text = bulletin;
					$bulletin.scale.set(1, 1);
					$bulletin.maxWidthHeight(
						bulletin_wordWrapWidth,
						$notify_icon.height * 1.2
					);
				},
				{ immediate: true }
			);

			/* 功能按钮的子窗口*/
			// 创建房间
			let _close_button_height;
			const $create_room_dialog = (() => {
				const dialog = new PIXI.Graphics();
				dialog.beginFill(0, 0.6);
				dialog.drawRect(0, 0, width, height);
				dialog.endFill(0);
				dialog.interactive = true;
				dialog.visible = false;
				stage.addChild(dialog);

				const bg = new PIXI.Sprite(
					resources.create_room_dialog.texture
				);
				bg.maxWidthHeight(width * 0.8, height * 0.8);
				bg.x = width / 2 - bg.width / 2;
				bg.y = height / 2 - bg.height / 2;
				const bg_bounds = bg.getBounds();
				dialog.addChild(bg);

				unwatchers[
					unwatchers.length
				] = this.$watch(
					"is_create_room_dialog_open",
					visible => {
						dialog.visible = visible;
					},
					{ immediate: true }
				);

				const title = new PIXI.Sprite(
					resources.create_room_title.texture
				);
				title.maxWidth(bg.width);
				title.x = bg.x;
				title.y = bg.y;
				dialog.addChild(title);

				const close_button = new PIXI.Sprite(
					resources.close_button.texture
				);
				close_button.maxHeight((_close_button_height = title.height));
				close_button.x = bg_bounds.right - close_button.width / 2;
				close_button.y = bg_bounds.y - close_button.height / 4;
				close_button.hover();
				close_button.bindTap(
					() => this.is_create_room_dialog_open = false
				);
				dialog.addChild(close_button);

				[
					"two_player",
					"three_player",
					"four_player"
				].forEach((room_type, i) => {
					const $button = new PIXI.Sprite(
						resources[room_type].texture
					);
					$button.maxWidth(bg.width / 4);
					$button.x = bg.x + (1 / 12 + i / 4 + i / 24) * bg.width;
					$button.y = bg.centerY - $button.height / 3;
					dialog.addChild($button);
					$button.bindTap(() => {
						this.player_number = 2 + i;
						this.createRoom();
					});
				});

				return dialog;
			})();
			// 加入游戏子窗口
			const $join_room_dialog = (() => {
				const dialog = new PIXI.Graphics();
				dialog.beginFill(0, 0.6);
				dialog.drawRect(0, 0, width, height);
				dialog.endFill(0);
				dialog.interactive = true;
				dialog.visible = false;
				stage.addChild(dialog);

				const bg = new PIXI.Sprite(resources.join_room_dialog.texture);
				bg.maxWidthHeight(width * 0.8, height * 0.8);
				bg.x = width / 2 - bg.width / 2;
				bg.y = height / 2 - bg.height / 2;
				const bg_bounds = bg.getBounds();
				dialog.addChild(bg);

				unwatchers[
					unwatchers.length
				] = this.$watch(
					"is_join_room_dialog_open",
					visible => {
						dialog.visible = visible;
					},
					{ immediate: true }
				);

				const close_button = new PIXI.Sprite(
					resources.close_button.texture
				);
				close_button.maxHeight(_close_button_height);
				close_button.x = bg_bounds.right - close_button.width / 2;
				close_button.y = bg_bounds.y - close_button.height / 4;
				close_button.hover();
				close_button.bindTap(
					() => this.is_join_room_dialog_open = false
				);
				dialog.addChild(close_button);

				const number_input = new PIXI.Sprite(
					resources.join_room_input.texture
				);
				number_input.maxWidth(bg.width * 0.8);
				number_input.y = bg.y + bg.height * 0.2;
				number_input.x = bg.x + bg.width * 0.1;
				dialog.addChild(number_input);
				const number_input_bounds = number_input.getBounds();

				for (let i = 0; i < 12; i += 1) {
					let num_button_value;
					if (i < 9) {
						num_button_value = i + 1;
					} else if (i === 9) {
						num_button_value = "reset";
					} else if (i === 10) {
						num_button_value = 0;
					} else if (i === 11) {
						num_button_value = "del";
					}
					const num_button = new PIXI.Sprite(
						resources["num_" + num_button_value].texture
					);
					num_button.maxWidth(bg.width / 4);
					num_button.x =
						(1 / 12 + i % 3 / 4 + i % 3 / 24) * bg.width + bg.x;
					num_button.y =
						number_input_bounds.bottom +
						Math.floor(i / 3) * num_button.height * 1.1 +
						number_input_bounds.height * 0.2;
					dialog.addChild(num_button);

					num_button.hover();
					if (typeof num_button_value === "number") {
						num_button.bindTap(() => {
							if (this.room_id.length < 4) {
								this.room_id += num_button_value;
							}
						});
					} else if (num_button_value === "reset") {
						num_button.bindTap(() => {
							this.room_id = "";
						});
					} else if (num_button_value === "del") {
						num_button.bindTap(() => {
							if (this.room_id.length) {
								this.room_id = this.room_id.substr(
									0,
									this.room_id.length - 1
								);
							}
						});
					}
				}

				const chars = [];
				for (let i = 0; i < 4; i += 1) {
					const char = loader.getNumberSprite(0, "big_numbers");
					char.maxHeight(number_input.height * 0.8);
					char.y = number_input.height * 0.1 + number_input.y;
					char.x =
						number_input.width * (i / 4 + 1 / 8) -
						char.width / 22 +
						number_input.x;
					dialog.addChild(char);
					chars.push(char);
				}
				const number_frames = new Map();
				for (let i = 0; i <= 9; i += 1) {
					number_frames.set(
						i,
						new PIXI.Rectangle(76 + i * 38, 0, 38, 49)
					);
				}

				unwatchers[
					unwatchers.length
				] = this.$watch(
					"room_id",
					room_id => {
						const room_id_chars = room_id.split("").slice(0, 4);
						chars.forEach(char => {
							char.visible = false;
						});
						room_id_chars.forEach((char_str, i) => {
							const char = chars[i];
							char.visible = true;
							char.setNumber(char_str);
						});
						if (room_id_chars.length === 4) {
							this.joinRoom();
						}
					},
					{ immediate: true }
				);

				return dialog;
			})();

			/* 功能按钮*/
			[
				"random_match",
				"create_room",
				"join_room"
			].forEach((button_type, i) => {
				const $button = new PIXI.Sprite(resources[button_type].texture);
				$button.maxWidth(width / 4);
				$button.x = (1 / 12 + i / 4 + i / 24) * width;
				$button.y = (height + header.height) / 2 - $button.height / 2;
				stage.addChildBefore($button, $create_room_dialog);
				if (button_type === "random_match") {
					$button.bindTap(() => this.joinQueue());
				} else if (button_type === "create_room") {
					$button.bindTap(
						() => this.is_create_room_dialog_open = true
					);
				} else if (button_type === "join_room") {
					$button.bindTap(() => this.is_join_room_dialog_open = true);
				}
			});

			/* 匹配模式的子窗口 */
			const $queue_room_dialog = (() => {
				const dialog = new PIXI.Graphics();
				dialog.beginFill(0, 0.6);
				dialog.drawRect(0, 0, width, height);
				dialog.endFill(0);
				dialog.interactive = true;
				dialog.visible = false;
				stage.addChild(dialog);

				const bg = new PIXI.Sprite(resources.random_queue_bg.texture);
				bg.maxWidthHeight(width * 0.8, height * 0.8);
				bg.x = width / 2 - bg.width / 2;
				bg.y = height / 2 - bg.height / 2;
				const bg_bounds = bg.getBounds();
				dialog.addChild(bg);

				const $cancel_btm = new PIXI.Sprite(
					resources.cancel_btm.texture
				);
				$cancel_btm.maxWidth(bg.width / 5);
				$cancel_btm.x = width / 2 - $cancel_btm.width / 2;
				$cancel_btm.y = bg.bottom - $cancel_btm.height * 1.5;
				$cancel_btm.hover();
				$cancel_btm.bindTap(() => this.cancelQueue());
				dialog.addChild($cancel_btm);

				const text_1 = "队列中";
				const text_2 = "等待确认,剩余TIME秒";
				const text_3 = "等待其它玩家确认,剩余TIME秒";
				const $queue_info = new PIXI.Text("匹配", {
					fontSize: $cancel_btm.width / 5,
					fill: 0xffffff
				});
				dialog.addChild($queue_info);

				// 确认按钮
				const $confirm_btm = new PIXI.Sprite(
					resources.confirm_btm.texture
				);
				$confirm_btm.maxWidth(bg.width / 5);
				$confirm_btm.x = width / 2 - $confirm_btm.width / 2;
				$confirm_btm.y = $cancel_btm.y - $confirm_btm.height * 1.5;
				$confirm_btm.hover();
				$confirm_btm.bindTap(() => this.confirmQueue());
				dialog.addChild($confirm_btm);

				const render_tpl_text = data => {
					data || (data = {});
					const { surplus_second = "" } = data;
					if ($queue_info._tpl_text) {
						const template_text = $queue_info._tpl_text;
						const new_text = template_text.replace(
							"TIME",
							surplus_second
						);
						if (new_text !== $queue_info.text) {
							$queue_info.text = new_text;

							$queue_info.x = width / 2 - $queue_info.width / 2;
							$queue_info.y = bg.centerY - $queue_info.height / 2;
						}
					}
				};

				let _queue_info_ti;
				unwatchers[
					unwatchers.length
				] = this.$watch(
					"player.status",
					status => {
						clearInterval(_queue_info_ti);
						_queue_info_ti = null;
						$confirm_btm.visible = false;
						if (status === PLAYER_STATUS.IN_QUEUE) {
							$queue_info._tpl_text = text_1;
							render_tpl_text(this.player.data);
						} else if (
							status === PLAYER_STATUS.BEFORE_QUEUE_TO_ROOM
						) {
							$queue_info._tpl_text = text_2;
							render_tpl_text(this.player.data);
							$confirm_btm.visible = true;
						} else if (
							status === PLAYER_STATUS.AFTER__QUEUE_TO_ROOM
						) {
							$queue_info._tpl_text = text_3;
							render_tpl_text(this.player.data);
						}
					},
					{ immediate: true }
				);

				unwatchers[
					unwatchers.length
				] = this.$watch("player.data", render_tpl_text, {
					immediate: true
				});

				return dialog;
			})();
			unwatchers[
				unwatchers.length
			] = this.$watch(
				"player.status",
				status => {
					if (
						status === PLAYER_STATUS.IN_QUEUE ||
						status === PLAYER_STATUS.BEFORE_QUEUE_TO_ROOM ||
						status === PLAYER_STATUS.AFTER__QUEUE_TO_ROOM
					) {
						$queue_room_dialog.visible = true;
					} else {
						$queue_room_dialog.visible = false;
					}
				},
				{ immediate: true }
			);

			/* 底部警示文字 */
			const warn_font_size = fontSize * 0.8;
			const $warn_text = new PIXI.Text(
				"抵制不良游戏, 拒绝盗版游戏, 注意自我保护, 谨防受骗上当, 适度游戏益脑, 沉迷游戏伤身, 合理安排时间, 享受健康生活",
				{
					fontSize: warn_font_size,
					dropShadow: true,
					dropShadowBlur: 3,
					dropShadowDistance: 2,
					dropShadowColor: 0x2233ff,
					fill: [0xb256c5, 0x9236a5],
					wordWrap: true,
					wordWrapWidth: width - warn_font_size * 2
				}
			);
			$warn_text.x = width / 2 - $warn_text.width / 2;
			$warn_text.y = height - $warn_text.height - fontSize;
			stage.addChild($warn_text);

			/*游戏日志对话框*/
			const $game_log_dialog = (() => {
				const dialog = new PIXI.Container();
				dialog.interactive = true;
				dialog.visible = false;
				stage.addChild(dialog);

				const bg = new PIXI.Sprite(resources.game_log_bg.texture);
				bg.interactive = true;
				bg.width = width;
				bg.height = height;
				dialog.addChild(bg);

				const close_button = new PIXI.Sprite(
					resources.game_log_close_btm.texture
				);
				close_button.alpha = 0.8;
				close_button.maxHeight(height * 0.1);
				close_button.x =
					width - close_button.width - close_button.height * 0.2;
				close_button.y = close_button.height * 0.2;
				close_button.hover();
				close_button.bindTap(() => this.is_game_log_open = false);
				const close_button_bounds = close_button.getBounds();
				dialog.addChild(close_button);

				const title = new PIXI.Sprite(resources.game_log_title.texture);
				title.maxWidthHeight(
					close_button_bounds.left -
						(width - close_button_bounds.left),
					height * 0.1
				);
				title.x = width / 2 - title.width / 2;
				title.y = close_button.centerY - title.height / 2;
				const title_bounds = title.getBounds();
				dialog.addChild(title);

				unwatchers[
					unwatchers.length
				] = this.$watch(
					"is_game_log_open",
					visible => {
						dialog.visible = visible;
					},
					{ immediate: true }
				);

				function formatDate(date) {
					var day = date.getDate();
					var monthIndex = date.getMonth();
					var year = date.getFullYear();

					return `${year} / ${monthIndex + 1} / ${day}`;
				}
				const $loading_info = new PIXI.Text("加载中", {
					fontSize,
					fill: 0xffffff
				});
				$loading_info.x = dialog.width / 2 - $loading_info.width / 2;
				$loading_info.y = dialog.height * 0.2;
				dialog.addChild($loading_info);

				unwatchers[
					unwatchers.length
				] = this.$watch(
					"is_game_log_loading",
					is_loading => {
						$loading_info.visible = is_loading;
					},
					{ immediate: true }
				);

				const $list = new PIXI.ScrollContainer({
					view_width: width,
					view_height: height * 0.8
				});
				// $list.y = height * 0.2;
				$list.y = 100; //height * 0.2;
				if (app._ticker.__list_hide_outele) {
					app._ticker.remove(app._ticker.__list_hide_outele);
				}

				app._ticker.add(
					(app._ticker.__list_hide_outele = () => {
						// 动画控制器
						$list.hideOffscreenElements();
					})
				);
				dialog.addChild($list);
				unwatchers[
					unwatchers.length
				] = this.$watch(
					"game_logs",
					game_logs => {
						$list.scrollContainer.children
							.slice()
							.forEach($c => $c.destroy());
						game_logs.forEach((game_log, i) => {
							const $item = new PIXI.Sprite(
								resources.game_log_item.texture
							);

							const fontSize = $item.height / 4;

							const $room_info = new PIXI.Text(
								`房号：${game_log.id}\n${formatDate(new Date(game_log.create_time))}`,
								{
									fontSize,
									fill: 0xffffff
								}
							);
							$room_info.x = $item.width * 0.05;
							$room_info.y =
								$item.height / 2 - $room_info.height / 2;
							$item.addChild($room_info);

							// 整理用户数据
							const players = JSON.parse(game_log.players_json);
							const player_map = new Map();
							players.forEach(player => {
								player.total = 0;
								player_map.set(player.id, player);
							});

							// 整理比分数据
							for (let flow_id in game_log.flows) {
								const flow = game_log.flows[flow_id];
								const results_list = JSON.parse(flow.data_json);
								results_list.forEach(results => {
									player_map.get(results.player_id).total +=
										results.total;
								});
							}
							players.forEach((player, i) => {
								const $player = new PIXI.Container();
								const $player_name = new PIXI.Text(
									player.info.username,
									{
										fontSize,
										fill: 0xffffff
									}
								);
								$player_name.x = -$player_name.width / 2;
								$player.addChild($player_name);

								let total_fill = 0xdddddd;
								if (player.total > 0) {
									total_fill = 0x00ff00;
								} else if (player.total < 0) {
									total_fill = 0xff0000;
								}
								const $player_total = new PIXI.Text(
									player.total,
									{
										fontSize,
										fill: total_fill
									}
								);
								$player_total.x = -$player_total.width / 2;
								$player_total.y =
									$player_name.height + fontSize / 2;
								$player.addChild($player_total);

								$player.x =
									$item.width *
									(0.3 +
										0.7 / (players.length + 1) * (i + 1));
								$player.y =
									$item.height / 2 - $player.height / 2;
								$item.addChild($player);
							});

							$item.maxWidth(dialog.width * 0.9);
							$item.x = width / 2 - $item.width / 2;
							$item.y =
								height * (0.02 + i * 0.02) + i * $item.height;

							$list.scrollContainer.addChild($item);
						});
					},
					{ immediate: true }
				);

				return dialog;
			})();
		};
	},
	mounted() {
		const query = queryString.parse();
		if (query.room) {
			const unwatchers = this.unwatchers;
			if (!window._auto_joined_room) {
				this.$watch(
					"player.info",
					player_info => {
						console.log(
							"auto join room",
							player_info,
							player_info.fake
						);
						if (!this.player.id) {
							return;
						}
						if (window._auto_joined_room) {
							return;
						}
						if (player_info.fake) {
							console.log("虚拟用户无法直接进入房间");
						} else {
							window._auto_joined_room = true;
							this.joinRoom({
								room_hash_id: query.room_hash_id,
								ignore_error: true,
								room_id: query.room
							});
						}
					},
					{ immediate: true }
				);
			}
		}
	},
	destroyed() {
		wx_promise.then(function(wx) {
			wx.onMenuShareAppMessage(window._wx_onMenuShareAppMessage_config);
		});
	},
	methods: {
		createRoom() {
			socket.emit("create-room", { player_number: this.player_number });
		},
		joinRoom(options) {
			socket.emit(
				"join-room",
				Object.assign({}, options, {
					room_id: this.room_id || options.room_id
				})
			);
		},
		joinQueue() {
			socket.emit("join-queue", { player_number: 4 });
		},
		confirmQueue() {
			socket.emit("confirm-queue-to-room");
		},
		cancelQueue() {
			socket.emit("cancel-queue");
		},
		async showGameLogPage() {
			this.is_game_log_open = true;
			this.is_game_log_loading = true;
			socket.emit("get-user-game-logs", {
				from: 0,
				limit: 10
			});
			socket.once("return-user-game-logs", data => {
				this.game_logs = data.list;
				this.is_game_log_loading = false;
			});
		}
	}
});
